<template>
  <div class="container">
    <Empty v-if="!$store.state.user.isLogin || !courses"></Empty>
    <van-tabs v-model="active" v-else @click="tabClick" color="#3ca7fa">
      <van-tab title="订阅课程"></van-tab>
      <van-tab title="收藏课程"></van-tab>
    </van-tabs>
    <van-list
      v-if="$store.state.user.isLogin"
      v-model="loading"
      :finished="finished"
      finished-text="已经到底了"
      @load="onLoad"
    >
      <div class="gray"></div>
      <VodCourse :courses="showCourses"></VodCourse>
    </van-list>
    <div class="btn-login" v-else @click="login">登录查看</div>
    <Tabbar></Tabbar>
  </div>
</template>

<script>
import Tabbar from '@/components/common/Tabbar';
import Empty from '@/components/common/Empty';
import VodCourse from '@/components/content/VodCourse';
import { getMemberCourses, getLikeCourses } from '@/network/study';

export default {
  components: {
    Tabbar,
    Empty,
    VodCourse,
  },
  data() {
    return {
      loading: false,
      finished: false,
      active: 0,
      courses: [],
      currentType: 'all',
      courses: {
        all: { page: 1, list: [] },
        like: { page: 1, list: [] },
      },
    };
  },
  methods: {
    login() {
      this.$router.push({ path: '/register', query: { url: location.href } });
    },
    tabClick(index) {
      const types = ['all', 'like'];
      if (this.currentType == types[index]) return;
      this.courses[this.currentType].list = [];
      this.courses[this.currentType].page = 1;
      this.currentType = types[index];
      this.loading = true;
      this.finished = false;
      this.onLoad();
    },
    onLoad() {
      if (!this.$store.state.user.isLogin) return;
      if (this.currentType == 'all') {
        getMemberCourses(this.courses[this.currentType].page).then((res) => {
          this.courses[this.currentType].list.push(...res.data.data);
          this.loading = false;
          this.courses[this.currentType].page += 1;
          if (this.courses[this.currentType].list.length >= res.data.total) {
            this.finished = true;
          }
        });
      } else {
        getLikeCourses(this.courses[this.currentType].page).then((res) => {
          this.courses[this.currentType].list.push(...res.data.data);
          this.loading = false;
          this.courses[this.currentType].page += 1;
          if (this.courses[this.currentType].list.length >= res.data.total) {
            this.finished = true;
          }
        });
      }
    },
  },
  computed: {
    showCourses() {
      return this.courses[this.currentType].list;
    },
  },
};
</script>

<style lang="less" scoped>
.btn-login {
  margin: 0 16px;
  height: 46px;
  line-height: 46px;
  font-size: 16px;
  text-align: center;
  color: #fff;
  border-radius: 4px;
  background-color: #3ca7fa;
}
.gray {
  height: 8px;
  background-color: #f3f6f9;
}
</style>
